在项目中通常有组织架构权限,地区,网站栏目都是树形结构的组织管理方式。在oracle中有相关特定语法可以解决,但是在mysql5中似乎没有相关的功能需要自己用sql实现。 mysql5的实现方式如下: 自上而下的查询:
select id,parent_id
from (
select t1.id,
t1.parent_id,
if(find_in_set(parent_id, @parentId) > 0, @parentId := concat(@parentId, ',', id), 0) as ischild
from (
select id, parent_id
from sys_organization t
where status = 1
) t1,
(select @parentId := 996) t2 -- 替换为#{parentId}
) t3
where ischild != 0;
自下而上的查询:
select id,parent_id
from (
select t1.id,
t1.parent_id,
if(parent_id is not null and id= @nid , @nid:=parent_id,0) as pid
from (
select id, parent_id
from sys_organization t
where status = 1 order by id desc
) t1,
(select @nid := 996) t2 -- 替换为#{parentId}
) t3
where pid!=0;
以上两种方式我们从sql的语法来看压根算不上是迭代,利用的是mysql的sql语法中的变量逐行赋值的特性,所以以上两个sql的字查询中都要对
d的排列顺序有要求的,如果表中父子id大小规律不明确以上sql会失效。这个方式就是全部查询id,再逐行筛选自己的父亲或者儿子。
如果使用的是mysql8版本的mysql
WITH RECURSIVE sys_organization_tree AS (
SELECT id,parent_id FROM sys_organization
WHERE parent_id = 996
UNION
SELECT e.id,e.parent_id FROM sys_organization e INNER JOIN sys_organization_tree s ON e.parent_id = s.id
) SELECT * from sys_organization_tree s
从996开始查询所有子节点的,同样查询上级id也很简单
|